<template>
  <div>
    <div class="consultation">
      <el-card class="box-card">
        <Search :searchType="searchType" @initiaSearch="initiaSearch"></Search>
        <el-button @click="addInit">新增初访</el-button>
        <!--表格信息展示-->
        <el-table ref="multipleTable" :row-class-name="tableRowClassName" :data="initiaList" tooltip-effect="dark"
          style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection"> </el-table-column>
          <el-table-column type="index" label="序号"> </el-table-column>
          <el-table-column prop="stuNum" label="学号" width="120"></el-table-column>
          <el-table-column prop="userInfo.stuName" label="姓名"></el-table-column>
          <el-table-column prop="userInfo.stuSex" :formatter="parseSex" label="性别" width="50"></el-table-column>
          <el-table-column prop="userInfo.stuAddress" label="校区" width="80"></el-table-column>
          <el-table-column prop="userInfo.stuMajor" label="学院" width="160"></el-table-column>
          <el-table-column prop="userInfo.stuPhone" label="电话" width="120"></el-table-column>
          <el-table-column prop="visitDate" label="初访周"></el-table-column>
          <el-table-column prop="visitTime" label="初访时间"></el-table-column>
          <el-table-column prop="visitRoom" label="初访地点" width="200"></el-table-column>
          <el-table-column prop="adminInfo.adminName" label="初访老师"></el-table-column>
          <el-table-column prop="visitStatus" :formatter="parseStatus" label="初访状态">
          </el-table-column>
          <el-table-column prop="visitResultCrisisStatus" :formatter="parseConclusion" label="初访结论"></el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button type="success" size="mini" icon="el-icon-circle-check" @click="examineTest(scope.row.visitId)"
                circle></el-button>
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="modify(scope.row.visitId)"
                circle></el-button>
              <el-popconfirm title="确定删除吗？" class="delete" @confirm="deleted(scope.row.visitId)">
                <el-button slot="reference" type="danger" size="mini" icon="el-icon-delete" circle></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 20px">
          <el-button @click="toggleSelection()">取消选择</el-button>
          <el-button @click="deleted(0)">删除</el-button>
        </div>
        <!--分页器-->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
          :page-sizes="[10, 20, 30, 40]" :page-size="limit" layout="total, sizes, prev, pager, next, jumper"
          :total="total" background>
        </el-pagination>
      </el-card>
      <el-dialog title="初访审核" :visible.sync="outerVisible">
        <el-descriptions class="margin-top" :column="2" border>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-user"></i>
              姓名
            </template>
            {{ initiaByone.userInfo?.stuName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-mobile-phone"></i>
              性别
            </template>
            {{ initiaByone.userInfo?.stuSex == 1 ? '男' : '女' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-office-building"></i>
              学号
            </template>
            {{ initiaByone.stuNum }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-location-outline"></i>
              校区
            </template>
            {{ initiaByone.userInfo?.stuAddress }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-tickets"></i>
              学院
            </template>
            {{ initiaByone.userInfo?.stuMajor }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-office-building"></i>
              电话
            </template>
            {{ initiaByone.userInfo?.stuPhone }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-office-building"></i>
              初访时间
            </template>
            {{ initiaByone.visitDate + initiaByone.visitTime }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-office-building"></i>
              初访地点
            </template>
            {{ initiaByone.visitRoom }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-office-building"></i>
              初访老师
            </template>
            {{ initiaByone.adminInfo.adminName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-office-building"></i>
              问卷评分
            </template>
            {{ initiaByone.visitCrisisGrades }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-office-building"></i>
              详细描述
            </template>
            {{ initiaByone.userCrisisText }}
          </el-descriptions-item>
        </el-descriptions>
        <div slot="footer" class="dialog-footer">
          <el-button @click="outerVisible = false">取 消</el-button>
          <el-button v-if="initiaByone.auditStatus == 0" type="primary" @click="pass(initiaByone.visitId)">通过</el-button>
          <el-button v-if="initiaByone.auditStatus == 0" type="primary"
            @click="dispass(initiaByone.visitId)">不通过</el-button>
        </div>
      </el-dialog>
      <el-dialog title="初访信息修改" :visible.sync="modifyVisible" width="20%" @close="close(0)">
        <el-form ref="form" :model="initiaByone" label-width="80px">
          <el-form-item label="初访周" prop="visitDate">
            <el-select v-model="initiaByone.visitDate" placeholder="请选择初访周" @change="GetTeacher(1)">
              <el-option value="周一"></el-option>
              <el-option value="周二"></el-option>
              <el-option value="周三"></el-option>
              <el-option value="周四"></el-option>
              <el-option value="周五"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="值班时间" prop="visitTime">
            <el-select v-model="initiaByone.visitTime" placeholder="请选择初访时间" @change="GetTeacher(1)">
              <el-option value="8:00-10:00"></el-option>
              <el-option value="10:00-12:00"></el-option>
              <el-option value="14:00-16:00"></el-option>
              <el-option value="16:00-18:00"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="值班地点" prop="visitRoom">
            <el-select v-model="initiaByone.visitRoom" placeholder="请选择值班地点" @change="GetTeacher(1)">
              <el-option value="宜宾校区b8a413"></el-option>
              <el-option value="汇南校区翻斗教室414"></el-option>
              <el-option value="宜宾校区智慧楼101"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="初访老师" prop="adminInfo.adminNum">
            <el-select v-model="initiaByone.adminInfo.adminNum" placeholder="请选择初访老师">
              <el-option v-for="item in teacherList" :key="item.adminInfo.adminNum" :label="item.adminInfo.adminName"
                :value="item.adminInfo.adminNum"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="close(0)">取 消</el-button>
          <el-button type="primary" @click="modifySumbit()">确认</el-button>
        </div>
      </el-dialog>
      <el-dialog title="新增初访信息" :visible.sync="addVisible" width="20%" @close="close(1)">
        <el-form ref="form" :model="addList" label-width="80px">
          <el-form-item label="学号" prop="userInfo.stuNum">
            <el-input class="long" v-model="addList.stuNum" placeholder="请输入学号"></el-input>
          </el-form-item>
          <el-form-item label="问卷分数" prop="visitCrisisGrades">
            <el-input class="long" v-model="addList.visitCrisisGrades" placeholder="请输入问卷分数"></el-input>
          </el-form-item>
          <el-form-item label="自述" prop="userCrisisText">
            <el-input class="long" type="textarea" v-model="addList.userCrisisText" placeholder="请输入自述"></el-input>
          </el-form-item>
          <el-form-item label="初访周" prop="visitDate">
            <el-select v-model="addList.visitDate" placeholder="请选择初访周" @change="GetTeacher(2)">
              <el-option value="周一"></el-option>
              <el-option value="周二"></el-option>
              <el-option value="周三"></el-option>
              <el-option value="周四"></el-option>
              <el-option value="周五"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="初访时间" prop="visitTime">
            <el-select v-model="addList.visitTime" placeholder="请选择初访时间" @change="GetTeacher(2)">
              <el-option value="8:00-10:00"></el-option>
              <el-option value="10:00-12:00"></el-option>
              <el-option value="14:00-16:00"></el-option>
              <el-option value="16:00-18:00"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="初访地点" prop="visitRoom">
            <el-select v-model="addList.visitRoom" placeholder="请选择初访地点" @change="GetTeacher(2)">
              <el-option value="宜宾校区b8a413"></el-option>
              <el-option value="汇南校区翻斗教室414"></el-option>
              <el-option value="宜宾校区智慧楼101"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="初访老师" prop="adminInfo.adminNum">
            <el-select v-model="addList.adminInfo.adminNum" placeholder="请选择初访老师">
              <el-option v-for="item in teacherList" :key="item.adminInfo.adminNum" :label="item.adminInfo.adminName"
                :value="item.adminInfo.adminNum"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="close(1)">取 消</el-button>
          <el-button type="primary" @click="addSumbit()">确认</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import Search from "@/components/search";
import { findStudentBy } from '@/api/Student'
import { reqGetWorkTotal, reqModifyStatus, reqModifyWorkNum } from '@/api/WorkTime'
import { reqAddInit, reqGetInitiaAll, reqGetInitiaTotal, reqGetById, reqDeletes, reqPass, reqModifyInit } from "@/api/InitiaVisit"
export default {
  data() {
    return {
      searchType: "初访",
      initiaByone: {
        adminInfo: {
          adminNum: ''
        }
      },
      //值班表信息
      workTimeList: {
        num: 2,
        isFree: 3,
        workAddress: '',
        workTime: '',
        workTeacherId: '',
        workDate: '',
        adminInfo: {
          adminName: ''
        }
      },
      initiaList: [],
      //选中行的编号
      rowsVisitId: [],
      //老师列表
      teacherList: [],
      //搜索列表
      SearchList: {
        stuNum: "",
        visitStatus: "",
        visitConclusion: "",
        visitDate: "",
        visitTime: "",
        adminInfo: {
          adminName: ""
        },
        userInfo: {
          stuName: "",
          stuAddress: "",
          stuMajor: "",
        }
      },
      //新增列表
      addList: {
        stuId: '',
        stuNum: '',
        visitCrisisGrades: '',
        visitTime: '',
        visitDate: '',
        visitRoom: '',
        userCrisisText: '',
        userInfo: {
          stuName: '',
        },
        adminInfo: {
          adminNum: ''
        }
      },
      //编辑前的数据
      modifyBefore: {
        adminInfo: {
          adminNum: "",
        },
        visitRoom: "",
        visitDate: "",
        visitTime: "",
        visitId: "",
      },
      visitStatusMap: {
        '3': '等待初访',
        '1': '初访中',
        '2': '初访结束'
      },
      visitConclusionMap: {
        '0': '转介送诊',
        '1': '安排咨询',
        '2': '无需咨询'
      },
      page: 1,
      limit: 10,
      total: 0,
      outerVisible: false,
      modifyVisible: false,
      addVisible: false,
    };
  },
  components: {
    Search,
  },
  methods: {
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //审核状态不同的颜色区分
    tableRowClassName({ row, rowIndex }) {
      if (row.auditStatus === 2) {
        return 'warning-row';
      } else if (row.auditStatus === 1) {
        return 'success-row';
      }
      return '';
    },
    //获取所有数据的总数
    async getTotal() {
      let result_Total = await reqGetInitiaTotal(this.SearchList);
      this.total = result_Total.data.length;
    },
    /*获取初访信息*/
    async getInitiaAll() {
      let result = await reqGetInitiaAll((this.page - 1) * this.limit, this.limit, this.SearchList);
      if (result.code == 0) {
        this.initiaList = JSON.parse(JSON.stringify(result.data));
      }
      this.getTotal();
    },
    //模糊查询
    async initiaSearch(visitInfo, num) {
      this.SearchList = JSON.parse(JSON.stringify(visitInfo));
      this.getInitiaAll();
      if (num == 0) {
        this.$message({
          message: '查询成功',
          type: 'success'
        });
      }
    },
    handleSelectionChange(selection) {
      this.rowsVisitId = selection.map(i => {
        return i.visitId;
      })
    },
    handleSizeChange(val) {
      this.limit = val
      this.getInitiaAll();
    },
    handleCurrentChange(val) {
      this.page = val
      this.getInitiaAll();
    },
    parseSex(row) {
      return row.userInfo.stuSex == 1 ? '男' : '女'
    },
    parseStatus(row) {
      return this.visitStatusMap[row.visitStatus]
    },
    parseConclusion(row) {
      return this.visitConclusionMap[row.visitResultCrisisStatus]
    },
    /*删除某行的数据*/
    async deleted(visitId) {
      let result;
      if (visitId != 0) {
        result = await reqDeletes([visitId]);
      } else {
        result = await reqDeletes(this.rowsVisitId);
      }
      if (result.code == 0) {
        this.getInitiaAll();
        this.$message({
          message: '删除成功',
          type: 'success'
        });
        this.rowsVisitId = [];
      }
    },
    //打开审核界面获取数据
    async examineTest(visitId) {
      this.outerVisible = true;
      let result = await reqGetById(visitId);
      if (result.code == 0) {
        this.initiaByone = JSON.parse(JSON.stringify(result.data));
      }
    },
    //动态刷新获取老师界面
    async GetTeacher(num) {
      //修改界面
      if (num != 2) {
        this.workTimeList.workDate = this.initiaByone.visitDate;
        this.workTimeList.workTime = this.initiaByone.visitTime;
        this.workTimeList.workAddress = this.initiaByone.visitRoom;
        let add = await reqGetWorkTotal(this.workTimeList);
        this.teacherList = add.data.filter(i => i.adminInfo.adminWorkStatus == 0);
        //第一次打开修改界面不刷新，只有修改数据后才刷新
        if (num == 1) {
          this.initiaByone.adminInfo.adminNum = ''
        }
      } else if (num == 2)//添加页面
      {
        this.workTimeList.workDate = this.addList.visitDate;
        this.workTimeList.workTime = this.addList.visitTime;
        this.workTimeList.workAddress = this.addList.visitRoom;
        let add = await reqGetWorkTotal(this.workTimeList);
        this.teacherList = add.data.filter(i => i.adminInfo.adminWorkStatus == 0);
        this.addList.adminInfo.adminNum = ''
      }
    },
    //打开修改界面
    async modify(visitId) {
      this.modifyVisible = true;
      let result = await reqGetById(visitId);
      if (result.code == 0) {
        this.initiaByone = JSON.parse(JSON.stringify(result.data));
      }
      this.modifyBefore={
        adminInfo: {
          adminNum: JSON.parse(JSON.stringify(this.initiaByone.adminInfo.adminNum)),
        },
        visitRoom: JSON.parse(JSON.stringify(this.initiaByone.visitRoom)),
        visitDate: JSON.parse(JSON.stringify(this.initiaByone.visitDate)),
        visitTime:JSON.parse(JSON.stringify(this.initiaByone.visitTime)),
        visitId: JSON.parse(JSON.stringify(this.initiaByone.visitId))
      }
      this.GetTeacher(0);
    },
    //审核通过
    async pass(visitId) {
      let result = await reqPass(visitId, 1, 3)
      if (result.code == 0) {
        this.getInitiaAll();
        this.getTotal();
        this.$message({
          message: '审核成功',
          type: 'success'
        });
        this.getInitiaAll();
        this.outerVisible = false;
      }
    },
    //审核不通过
    async dispass(visitId) {
      let result = await reqPass(visitId, 2, -1)
      if (result.code == 0) {
        this.getInitiaAll();
        this.getTotal();
        this.$message({
          message: '审核不通过',
        });
        this.outerVisible = false;
      }
    },
    //提交修改
    async modifySumbit() {
      let modifyList = {
        adminInfo: {
          adminNum: this.initiaByone.adminInfo.adminNum
        },
        visitRoom: this.initiaByone.visitRoom,
        visitDate: this.initiaByone.visitDate,
        visitTime: this.initiaByone.visitTime,
        visitId: this.initiaByone.visitId
      };
      let modifyResult = await reqModifyInit(modifyList);
      if (modifyResult.code == 0) {
        this.getInitiaAll();
        this.$message({
          message: '提交成功',
          type: 'success'
        });
        this.modifyVisible = false;
        this.isFree(modifyList);
        this.modifyBefore = JSON.parse(JSON.stringify(modifyList))
      }

    },
    //打开新增列表
    addInit() {
      this.addVisible = true;
    },
    //提交新增
    async addSumbit() {
      let stu = await findStudentBy(this.addList.stuNum);
      try {
        this.addList.stuId = stu.data.data[0].stuId;
        this.addList.userInfo.stuName = stu.data.data[0].stuName;
      } catch {
        this.$message({
          message: '请输入正确或者已有的学号账号',
          type: 'warning'
        });
        return
      }
      let result = await reqGetInitiaTotal(this.addList)
      if (result.data.filter(i => i.auditStatus == 0).length != 0) {
        this.$message({
          message: '该时间段该学生已有预约',
          type: 'warning'
        });
        return
      }
      let addResult = await reqAddInit(this.addList);
      if (addResult.code == 0) {
        this.$message({
          message: '添加成功',
          type: 'success'
        })
        this.getInitiaAll();
      };
      this.addVisible = false;
    },
    //关闭新增页面
    close(num) {
      if (num == 1) {
        this.addVisible = false;
        this.addList = {
          stuId: '',
          stuNum: '',
          visitCrisisGrades: '',
          visitTime: '',
          visitDate: '',
          visitRoom: '',
          userCrisisText: '',
          userInfo: {
            stuName: '',
          },
          adminInfo: {
            adminNum: ''
          }
        }
      } else if (num == 0) {
        this.modifyVisible = false;
      }
      this.teacherList = []
    },
    //判断并修改值班表忙碌空闲状态
    async free(modifyList) {
      let result_Total = await reqGetInitiaTotal(this.SearchList);
      //筛选出在该值班下有多少初访信息
      let filterList = result_Total.data.filter(i => {
        return (i.visitDate == modifyList.visitDate && i.visitTime == modifyList.visitTime && i.visitRoom == modifyList.visitRoom
          && i.visitAdminId == modifyList.adminInfo.adminNum)
      })
      if (filterList.length > 3) {
        return
      };
      //修改值班信息的预约人数
      let num = 3 - filterList.length;
      let workNum;
      let workBusy;
      //获取该信息下的值班表所属的值班编号
      let workTime = await reqGetWorkTotal({
        num: 2,
        workAddress: modifyList.visitRoom,
        workTime: modifyList.visitTime,
        isFree: 3,
        workTeacherId: modifyList.adminInfo.adminNum,
        workDate: modifyList.visitDate,
        adminInfo: {
          adminName: ''
        }
      })
      //若立刻取不到值，只有num不为0且忙碌下才会进行此函数报错，则为忙碌预约值班改为空闲预约值班的情况
      try {
        workNum = workTime.data[0].workNum;
      } catch {
        workBusy = await reqGetWorkTotal({
          num: 2,
          workAddress: modifyList.visitRoom,
          workTime: modifyList.visitTime,
          isFree: 2,
          workTeacherId: modifyList.adminInfo.adminNum,
          workDate: modifyList.visitDate,
          adminInfo: {
            adminName: ''
          }
        })
        workNum = workBusy.data[0].workNum;
      }
      //如果为0且为当前修改状态，则修改值班状态为忙碌
      if (num == 0) {
        await reqModifyStatus(workNum, 2)
      } else {
        await reqModifyStatus(workNum, 3) //如果仍未到三人预约，或为前一次修改
      }
      //修改值班的预约人数
      await reqModifyWorkNum(workNum, num)
    },
    isFree(modifyList) {
      this.free(modifyList);
      this.free(this.modifyBefore);
    }
  },
  created() {
    this.getInitiaAll()
  }
};
</script>
<style scoped>
.delete {
  margin-left: 10px;
}

.el-table /deep/ .warning-row {
  background: oldlace;
}

.el-table /deep/ .success-row {
  background: #f0f9eb;

}

.long.el-input {
  width: 200px
}
</style>
